<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: 16 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <!-- 默认排序, 降序descending-->
        <el-table border :data="list" :default-sort="{prop:'timeOfEntry', order: 'descending' }">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ hireTypeFormat(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="账户状态" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <div style="height: 60px; margin-top: 10px">
            <!-- 分页 -->
            <el-pagination
              :current-page="page"
              layout="total, sizes,prev, pager, next, jumper"
              :total="total"
              :page-size="size"
              :page-sizes="[2,5,10,20]"
              @current-change="hCurrentChange"
              @size-change="hSizeChange"
            />
          </div>
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <emp-dialog ref="EmpDialog" @success="hSuccess" @close="showDialog=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import PageTools from '@/components/PageTools'
import { getEmployeeList, delEmployee } from '@/api/employee'
import employeeEnum from '@/constant/employees'
// import addorEdit from './empDialog'
import EmpDialog from './empDialog.vue'
const hireType = {}
employeeEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
})
// const hireType = employeeEnum.hireType.reduce((acc, item) => {
//   hireType[item.id] = item.value
//   return acc
// }, {})
export default {
  components: {
    PageTools, EmpDialog
  },
  data() {
    return {
      list: [],
      size: 5,
      page: 2,
      total: 0,
      showDialog: false
    }
  },
  created() {
    this.loadEmployee()
  },
  methods: {
    // 加载员工信息
    async loadEmployee() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        if (res.code === 10000) {
          this.list = res.data.rows
          this.total = res.data.total
        }
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    },
    hireTypeFormat(data) {
      // return employeeEnum.hireType.find(item => item.id === data).value
      return hireType[data] || '未知'
    },
    // 每控制每页条数的切换
    hSizeChange(val) {
      // 更新每页的条数
      this.page = 1
      this.size = val
      this.loadEmployee()
    },
    // 控制页码值的切换
    hCurrentChange(val) {
      // 更新页码
      this.page = val
      this.loadEmployee()
    },
    hSuccess() {
      this.total++
      // 获取到最大页码值
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployee()
      this.showDialog = false
    },
    // 重置表单
    hClose() {
      this.$refs.EmpDialog.resetForm()
    },
    // 删除员工
    hDel(id) {
      this.$confirm('您确认要进行删除吗?').then(async() => {
        const res = await delEmployee(id)
        console.log(res)
        if (this.list.length === 1) {
          this.page--
        }
        if (this.page <= 0) {
          this.page = 1
        }
        this.loadEmployee()
      }).catch(err => err)
    },
    dataFormat(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 获取表头
      const one = list[0]
      let header = []
      // 如果list中有数组，需要生成表头
      if (one) {
        header = Object.keys(one).map(enkey => {
          return mapInfo[enkey]
        })
      }
      // 2. 生成data数据
      // 将每一个对象中的值存到一个数组中,将每个位置存储到最大数组中
      const data = list.map(item => {
        return Object.values(item)
      })
      return { header, data }
    },
    async  handleDownload() {
      // 1.发送请求获取数据
      try {
        const res = await getEmployeeList(this.page, this.size)
        if (res.code !== 10000) return
        console.log(res.data.rows)
        const { header, data } = this.dataFormat(res.data.rows)
        import('@/vendor/Export2Excel').then(excel => {
          excel.export_json_to_excel({
            header,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
        console.log('getEmployeeList', res)
        // 保存数据
      } catch (err) {
        console.log('getEmployeeList', err)
      }
    }

  }
}
</script>
